//
//  HomeController.swift
//  微博项目
//
//  Created by admin on 16/3/2.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class HomeController: UITableViewController,CoverDelegate {
    lazy var menu:MenuTableController = MenuTableController()
    weak var popMenu:PopMenu?
    lazy var statuses:[StatusCellFrame] = []
    weak var messageView:UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setNav()
        self.setRefresh()
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        self.setMessage()
    }
    
    func setMessage()
    {
        let messageH:CGFloat = 44
        let temp = UILabel(frame: CGRectMake(0, 0, ScreenW, messageH))
        temp.backgroundColor = UIColor(patternImage: UIImage(imageLiteral: "timeline_new_status_background"))
        temp.textAlignment = NSTextAlignment.Center
        self.navigationController?.navigationBar.addSubview(temp)
        self.navigationController?.navigationBar.sendSubviewToBack(temp)
        self.messageView = temp
    }
    override func viewWillLayoutSubviews() {
        self.tableView.backgroundColor = UIColor.lightGrayColor()
    }
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool
    {
        return false
    }
    func showMessage(messageCount:Int)
    {
        self.messageView.text = "有\(messageCount)条消息"
        UIView.animateWithDuration(2, animations: { () -> Void in
                self.messageView.transform = CGAffineTransformMakeTranslation(0, self.messageView.frame.size.height)
            }) { [weak self] (bool:Bool) -> Void in
                UIView.animateWithDuration(2, delay: 1, options: UIViewAnimationOptions.CurveEaseIn, animations: { [weak self] () -> Void in
                        self!.messageView.transform = CGAffineTransformIdentity
                    }, completion: { (bool:Bool) -> Void in
                        
                })
        }
    }
    func setRefresh()
    {
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewStatus")
        self.tableView.mj_header.beginRefreshing()
        self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadOldStatus")
        self.tableView.mj_footer.backgroundColor = UIColor.clearColor()
        self.tableView.registerClass(StatusCell.self, forCellReuseIdentifier: self.cellIdentifier)
    }
    // 加载更新的微博
    func loadNewStatus()
    {
        let requestStatusParameter = RequestStatusParameter(since_id: 0, max_id: 0, count: 10)
        if self.statuses.count > 0
        {
            requestStatusParameter.since_id = (self.statuses.first!.status.id)!
        }
        StatusTool.getNewStatus(requestStatusParameter, progressParameter: { (progress:NSProgress) -> Void in
            
            }, successParameter: { (statuses:[StatusCellFrame]?) -> Void in
                if statuses?.count > 0
                {
                    self.showMessage((statuses?.count)!)
                    // 去掉提醒
                    ((self.tabBarController as! JinTabbarController).myTabBar?.viewWithTag(1) as! TabbarButton).badge.badge = 0
                    print(((self.tabBarController as! JinTabbarController).myTabBar?.viewWithTag(1) as! TabbarButton).badge.badge)
                }
                self.statuses = statuses! + self.statuses
                self.tableView.reloadData()
                self.tableView.mj_header.endRefreshing()
            }) { (task:NSURLSessionDataTask?, error:NSError) -> Void in
                print(error)
        }
    }
    // 加载更旧的微博
    func loadOldStatus()
    {
        if self.statuses.count > 0
        {
            let requestStatusParameter = RequestStatusParameter(since_id: 0, max_id: Int(self.statuses.last!.status.id) - 1, count: 10)
            StatusTool.getNewStatus(requestStatusParameter, progressParameter: { (progress:NSProgress) -> Void in
                
                }, successParameter: { (statuses:[StatusCellFrame]?) -> Void in
                    self.statuses = self.statuses + statuses!
                    self.tableView.reloadData()
                    self.tableView.mj_footer.endRefreshing()
                }) { (task:NSURLSessionDataTask?, error:NSError) -> Void in
                    print(error)
            }
        }
    }
    func setNav()
    {
        let leftbutton = UIBarButtonItem(image: UIImage(imageLiteral: "navigationbar_friendsearch"), hilightedImage: UIImage(imageLiteral: "navigationbar_friendsearch_highlighted"), target: nil, action: nil)
        let rightbutton = UIBarButtonItem(image: UIImage(imageLiteral: "navigationbar_pop"), hilightedImage: UIImage(imageLiteral: "navigationbar_pop_highlighted"), target: self, action: "push")
        self.navigationItem.leftBarButtonItem = leftbutton
        self.navigationItem.rightBarButtonItem = rightbutton
        
        let titleView = NavTitleButton(type: UIButtonType.Custom)
        titleView.setImage(UIImage(imageLiteral: "navigationbar_arrow_up"), forState: UIControlState.Normal)
        titleView.setImage(UIImage(imageLiteral: "navigationbar_arrow_down"), forState: UIControlState.Selected)
        titleView.setTitle(self.title, forState: UIControlState.Normal)
        titleView.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        titleView.setBackgroundImage(UIImage(imageLiteral: "navigationbar_filter_background_highlighted").stretchableImageWithLeftCapWidth(2, topCapHeight: 2), forState: UIControlState.Highlighted)
        titleView.sizeToFit()
        titleView.addTarget(self, action: Selector("titleClick:"), forControlEvents: UIControlEvents.TouchDown)
        self.navigationItem.titleView = titleView
    }
    // 进入下个控制器
    func push()
    {
        let controller = OneController()
        self.navigationController?.pushViewController(controller, animated: true)
    }
    // 标题点击事件
    func titleClick(button:NavTitleButton)
    {
        let temp = self.navigationItem.titleView as! UIButton
        temp.selected = !temp.selected
        let cover = Cover.show()
        cover.coverDelegate = self
        let menuW:CGFloat = 200
        self.popMenu = PopMenu.show(CGRectMake((UIScreen.mainScreen().bounds.size.width - menuW) * 0.5, CGRectGetMaxY((self.navigationController?.navigationBar.frame)!), menuW, 300))
        self.popMenu!.addSubview(self.menu.tableView)
        
    }
    // 蒙板点击事件
    func coverClick() {
        let temp = self.navigationItem.titleView as! NavTitleButton
        temp.selected = !temp.selected
        self.popMenu?.removeFromSuperview()
    }
    
    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.statuses.count
    }
    let cellIdentifier = "reuseIdentifier"
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:StatusCell? = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as! StatusCell
        // Configure the cell...
        cell?.statusFrame = self.statuses[indexPath.row]
        return cell!
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return self.statuses[indexPath.row].cellH!
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
